$(function () {
  bindUserToForm()
  //用户名失去焦点时执行的验证操作
  $('#userName').blur(checkUserName)
  //生日验证
  $('#date').blur(checkBirthday)
  //验证电话
  $('#userphone').blur(checkPhone)
  //验证地址
  $('#userAddress').blur(checkAddress)
  //表单提交
  $('.updateForm').submit(function (e) {
    e.preventDefault()
    //判断当前的表单验证是否通过
    let flag = checkUserName() & checkBirthday() & checkPhone() & checkAddress()
    if (flag === 0) {
      return alert('请正确填写修改信息')
    }
    //提交表单进行修改操作
    updateUser()
  })
})

/**
 * 修改用户信息的函数
 * @date 2021-05-08
 * @returns {any}
 */
async function updateUser() {
  let {
    id
  } = getParams()
  //准备参数
  let options = {
    url: 'http://146.56.230.35:3007/users/updateUserById',
    type: 'PUT',
    data: {
      id: parseInt(id),
      userName: $('#userName').val().trim(),
      gender: $('.gender').val() === '男' ? 1 : 2,
      birthday: $('#date').val().trim(),
      address: $('#userAddress').val().trim(),
      userRole: parseInt($('.role:checked').val()),
      phone: $('#userphone').val().trim(),
    },
  }
  console.log(options)
  //发起修改请求
  let res = await request(options)
  if (res.code !== 200) {
    return alert(res.msg)
  }
  //修改成功，跳转到用户列表页面
  location = 'userList.html'
}

/**
 * 验证地址
 * @date 2021-05-08
 * @returns {any}
 */
function checkAddress() {
  let address = $('#userAddress')
  let v = address.val().trim()
  let parent = address.parent()
  let span = address.next()
  span.empty()
  //判断非空
  if (!v) {
    parent.removeClass('ok').addClass('error')
    span.html('地址不能空')
    return false
  }
  parent.removeClass('error').addClass('ok')
  span.html('地址正确')
  return true
}

/**
 * 验证电话
 * @date 2021-05-08
 * @returns {any}
 */
function checkPhone() {
  let phone = $('#userphone')
  let v = phone.val().trim()
  let parent = phone.parent()
  let span = phone.next()
  span.empty()
  //判断非空
  if (!v) {
    parent.removeClass('ok').addClass('error')
    span.html('电话不能空')
    return false
  }
  let reg = /^1[3456789]\d{9}$/
  if (!reg.test(v)) {
    parent.removeClass('ok').addClass('error')
    span.html('电话号码非法')
    return false
  }
  parent.removeClass('error').addClass('ok')
  span.html('电话正确')
  return true
}

/**
 * 验证生日
 * @date 2021-05-08
 * @returns {any}
 */
function checkBirthday() {
  let birthday = $('#date')
  let v = birthday.val().trim()
  let parent = birthday.parent()
  let span = birthday.next()
  span.empty()
  //判断非空
  if (!v) {
    parent.removeClass('ok').addClass('error')
    span.html('生日不能为空')
    return false
  }
  //判断是否符合格式yyyy-mm-dd
  let reg = /^\d{1,4}-\d{2}-\d{2}$/
  if (!reg.test(v)) {
    parent.removeClass('ok').addClass('error')
    span.html('生日的格式是yyyy-mm-dd')
    return false
  }
  let arr = v.split('-')
  arr.map((item) => {
    item = parseInt(item)
  })
  //截取年
  let year = arr[0]
  let now = new Date().getFullYear()
  if (year > now || year < 0) {
    parent.removeClass('ok').addClass('error')
    span.html(`生日的年份必须在0-${now}之间`)
    return false
  }
  //截取月
  let month = arr[1]
  if (month > 12 || month < 1) {
    parent.removeClass('ok').addClass('error')
    span.html(`生日的月份必须在1-12之间`)
    return false
  }
  //截取日
  let day = arr[2]
  let date = 28
  //判断闰年
  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    date = 29
  }
  let maxDate = [31, date, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  if (day < 1 || day > maxDate[month - 1]) {
    parent.removeClass('ok').addClass('error')
    span.html(`生日的日期必须在1-${maxDate[month - 1]}之间`)
    return false
  }
  parent.removeClass('error').addClass('ok')
  span.html('生日正确')
  return true
}

/**
 * 验证用户名 全英文或全中文 2-16位
 * @date 2021-05-08
 * @returns {any}
 */
function checkUserName() {
  let userName = $('#userName')
  let v = userName.val()
  let parent = userName.parent()
  let span = userName.next()
  span.empty()
  //判断空
  if (!v) {
    parent.removeClass('ok').addClass('error')
    span.html('用户名不能为空')
    return false
  }
  //全英文或全中文 2-16位
  let reg = /^([\u4e00-\u9fa5]{2,16})$|^([a-zA-Z_$]{2,16})$/
  if (!reg.test(v)) {
    parent.removeClass('ok').addClass('error')
    span.html('用户名全英文或全中文2-16位')
    return false
  }
  parent.removeClass('error').addClass('ok')
  span.html('用户名正确')
  return true
}

async function bindUserToForm() {
  let user = await getUserById()
  if (!user) {
    return
  }
  //把用户的信息填充到表单中
  $('#userName').val(user.userName)
  //性别
  let genders = $('.gender>option')
  genders.each(function (index, item) {
    item.selected = false
    if (item.value === user.gender) {
      item.selected = true
    }
  })
  //生日
  $('#date').val(dateformat(user.birthday))
  //电话
  $('#userphone').val(user.phone)
  //地址
  $('#userAddress').val(user.address)
  //设置用户角色
  let role = $('.role')
  role.each(function (index, item) {
    //item是原生的js对象
    //item.value  ---> $(item).val()
    item.checked = false
    if (parseInt(item.value) === user.userRole) {
      item.checked = true
    }
  })
}

async function getUserById() {
  let {
    id
  } = getParams() //{id:'40'} 对象解构
  if (!id) {
    return null
  }
  //准备参数
  let options = {
    url: 'http://146.56.230.35:3007/users/getUserById',
    type: 'GET',
    data: {
      id: parseInt(id)
    },
  }
  try {
    let res = await request(options)
    if (res.code !== 200) {
      alert(res.msg)
      return null
    }
    return res.user
  } catch (error) {
    return null
  }
}

//获得url中的查询参数
function getParams() {
  //?id=40&name=tom
  let search = location.search
  if (!search) {
    return null
  }
  search = search.substring(1)
  let index = search.indexOf('&')
  let object = {}
  if (index === -1) {
    let arr = search.split('=')
    object[arr[0]] = arr[1]
  } else {
    //id=40&name=tom--->arr=['id=40','name=tom']
    let arr = search.split('&')
    for (let i = 0; i < arr.length; i++) {
      //'id=40'
      let item = arr[i]
      //'id=40'--->['id','40']
      let array = item.split('=')
      object[array[0]] = array[1]
    }
  }
  return object
}

function dateformat(v) {
  v = v ? new Date(v) : new Date()
  let str = v.getFullYear() + '-'
  str += (v.getMonth() + 1 + '').padStart(2, '0') + '-'
  str += (v.getDate() + '').padStart(2, '0') + ' '
  return str
}

/*
  1)this永远是原生的js对象
  2)把原生的js对象，转换成jquery对象
    this ---> $(this)
  3)for循环中的
    let that =  $('.role')
    for(let i = 0;i<that.length;i++){
      that[i] //数组原生是原生的js对象
    }
  4) each回调函数中的item是原生的js对象
  5) 把jquery对象转换成js原生对象
    $('.role').get(index) //index>=0的整数
    $('.role').[index]
*/